/*
 * Copyright (c) 2014-2015 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.util;

import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.User;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utility class that provide static methods to work with passwords.
 *
 * @Author Alessandro Cantini
 */
public class HashUtils {

	private HashUtils() {
	}

	/**
	 * Produces the hash of a password using SHA-256 algorithm.
	 *
	 * @param password the password to encrypt
	 * @return the hash of the specified password
	 */
	public static String encryptPassword(String password) {
		String encryptedPass = null;

		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(password.getBytes("UTF-8"));
			BigInteger bigInt = new BigInteger(1, hash);
			encryptedPass = bigInt.toString(16);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
			Logger.getLogger(HashUtils.class.getName()).log(Level.SEVERE, "Error encrypting password", ex);
		}

		return encryptedPass;
	}

	public static String createToken(User user) {
		Random random = new Random();
		String toHash = user.getEmail() + random.nextLong();
		return encryptPassword(toHash);
	}
}
